#include "../StdAfx.h"
#include "Util.h"
#include "Config.h"

#include "XMLParser.h"

#ifndef UNDER_CE
#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
#endif

#include "../debug_new.h"

HWND CUtil::m_hWndBc = NULL;
UINT CUtil::m_wMsgBc = NULL;
WPARAM CUtil::m_wParamBc = NULL;
LPARAM CUtil::m_lParamBc = NULL;
BroadcastType CUtil::m_BcType = BC_VISIBLE;

HMODULE CUtil::g_ResDll = NULL;
wstring CUtil::g_strResPath = L"";

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
/**///////////////////////////////////////////////////////////////////////

CUtil::CUtil()
{

}

CUtil::~CUtil()
{

}

//---------------------------------------------------------------------
//Description:
//    Show or hide the task bar
//
//Parameters:
//    bShow:[in]
//        TRUE -- Show the task bar
//        FALSE -- Hide the task bar
//---------------------------------------------------------------------
BOOL CUtil::ShowTaskBar(BOOL bShow)
{
    HWND hWndTask = FindWindow(TEXT("HHTaskBar"),NULL);
    if(hWndTask == NULL)
    {
        return FALSE;
    }

    if(bShow == TRUE)
    {
        ShowWindow(hWndTask,SW_SHOW);
    }
    else
    {
        ShowWindow(hWndTask,SW_HIDE);
    }

    return TRUE;
}


//---------------------------------------------------------------------
//Description:
//    Execute the application
//
//Parameters:
//    pszPath:[in] Long pointer to a null-terminated string that specifies the absolute name of the file to run
//    pParameters:[in] Long pointer to a null-terminated string that contains the application parameters. 
//                The parameters must be separated by spaces. To include double quotation marks, 
//                you must enclose the marks in double quotation marks, as in the following example. 
//                TCHAR *pParameters = "An example: """quoted text"""";
//                In this case, the application receives three parameters: An, example:, and "quoted text". 
//                If the pszPath specifies a document file, this member should be NULL. 
//
//---------------------------------------------------------------------
#include "shellapi.h"

BOOL CUtil::Execute(const TCHAR *pszPath,TCHAR *pParameters)
{
	BOOL nRet = FALSE;
	//PROCESS_INFORMATION  info;
	//nRet = CreateProcess(pszPath,pParameters,NULL,NULL,FALSE,0,NULL,NULL,NULL,&info);
	//if(nRet)
	//{
	//	CloseHandle(info.hThread);
	//	CloseHandle(info.hProcess);
	//}	

#ifdef UNDER_CE
    SHELLEXECUTEINFO info;    
    memset(&info,0,sizeof(info));
    info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
    info.lpVerb = NULL;
    info.lpFile = pszPath;
    info.lpParameters = pParameters;
    info.lpDirectory = NULL;
    info.nShow = SW_SHOW;
    info.hInstApp = NULL;
	info.hwnd = NULL;
    info.cbSize = sizeof( info );
    nRet = ShellExecuteEx( &info );    
#else
	nRet = (BOOL)ShellExecute(NULL,L"open",pszPath,pParameters,NULL,SW_SHOWNORMAL); 
#endif

    return nRet;
}

//---------------------------------------------------------------------------
//Description:
//    Find the string in the source string ,and return the position.
//
//Parameter:
//    szSource:[in] 
//        The source string
//    szFind:[in]
//        The find string
//    iBeginPos:[in]
//        The begin finding position
//
//Return Values:
//    If it -1 , couldn't find the string.
//    Others , it's the position of the first character of szFind in the source string
//
//---------------------------------------------------------------------------
int CUtil::FindString(const TCHAR *szSource, const TCHAR *szFind, const int iBeginPos)
{
    int iLenSource = _tcslen(szSource);
    int iLenFind = _tcslen(szFind);

    if(iLenSource - 1 < iBeginPos)
    {
        return -1;
    }

    int iCount = 0;
    int iFindCount = 0;
    BOOL bPair = FALSE;
    for(iCount = 0; iCount < iLenSource - iBeginPos; iCount++)
    {
        if(szSource[iCount + iBeginPos] == szFind[iFindCount])
        {
            if(iFindCount == iLenFind - 1)
            {
                bPair = TRUE;
                break;
            }
            iFindCount++;            
        }
        else
        {
            iFindCount = 0;
        }
    }

    int iFindPos ;

    if(bPair == FALSE)
    {
        iFindPos = -1;
    }
    else
    {
        iFindPos = iCount + iBeginPos - iLenFind + 1;
    }
    return iFindPos;
}


//-------------------------------------------------------------------------------------
//Description:
//    Get the current runing path including '' in last
//
//Parameters:
//    pszPath: [out] Get the current path
//    ulSize: [in] The size of the buffer. For example: szPath[MAX_NUMBER],the size if MAX_NUMBER.
//
//-------------------------------------------------------------------------------------
wstring CUtil::GetCurrentDirectory(/*TCHAR *pszPath, ULONG ulSize*/)
{
    //memset(pszPath, 0, sizeof(TCHAR) * ulSize);

    TCHAR szBuf[MAX_PATH] =  {0};

    GetModuleFileName(NULL,szBuf,sizeof(szBuf)/sizeof(TCHAR));

    ULONG ulCount = _tcslen(szBuf);
    while(--ulCount >= 0)
    {
        if(szBuf[ulCount] == '\\')
        {
			 szBuf[ulCount] = 0;
            break;
        }
        else
        {
            continue;
        }
    }

    return wstring(szBuf);
}

//-------------------------------------------------------------------------------------
//Description:
//    Get screen width in pixels
//------------------------------------------------------------------------------------
int CUtil::GetScreenWidth()
{
#ifdef UNDER_CE
    return GetSystemMetrics(SM_CXSCREEN);
#else
//	return 800;
	return 1024;
	//return 320; 
#endif
}


//-------------------------------------------------------------------------------------
//Description:
//    Get screen height in pixels
//------------------------------------------------------------------------------------
int CUtil::GetScreenHeight()
{
#ifdef UNDER_CE
    return GetSystemMetrics(SM_CYSCREEN);
#else
//	return 480;
	return 600;
	//return 240;
#endif
}

//-------------------------------------------------------------------------------------
//Description:
//    Center the window.
//
//Parameters:
//    hWnd:[in] The window to be moved
//------------------------------------------------------------------------------------
BOOL CUtil::CenterWindow(HWND hWnd)
{
    if(hWnd == NULL)
    {
        return FALSE;
    }

    RECT rcWnd =  {0};
    if(GetWindowRect(hWnd,&rcWnd) == FALSE)
    {
        return FALSE;
    }

    int iWidth = rcWnd.right - rcWnd.left;
    int iHeight = rcWnd.bottom - rcWnd.top;
    int iX = (GetScreenWidth() - iWidth) / 2;
    int iY = (GetScreenHeight() - iHeight) / 2;

    return MoveWindow(hWnd,iX,iY,iWidth,iHeight,TRUE);
}


//-------------------------------------------------------------------------------------
//Description:
//    This function maps a character string to a wide-character (Unicode) string
//
//Parameters:
//    lpcszStr: [in] Pointer to the character string to be converted 
//    lpwszStr: [out] Pointer to a buffer that receives the translated string. 
//    dwSize: [in] Size of the buffer
//
//Return Values:
//    TRUE: Succeed
//    FALSE: Failed
//    
//Example:
//    MByteToWChar(szA,szW,sizeof(szW)/sizeof(szW[0]));
//---------------------------------------------------------------------------------------
BOOL CUtil::MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
{
    // Get the required size of the buffer that receives the Unicode 
    // string. 
    DWORD dwMinSize;
    dwMinSize = MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, NULL, 0);

    if(dwSize < dwMinSize)
    {
        return FALSE;
    }

    // Convert headers from ASCII to Unicode.
    MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, lpwszStr, dwMinSize);  
    return TRUE;
}


//-------------------------------------------------------------------------------------
//Description:
//    This function maps a wide-character string to a new character string
//
//Parameters:
//    lpcwszStr: [in] Pointer to the character string to be converted 
//    lpszStr: [out] Pointer to a buffer that receives the translated string. 
//    dwSize: [in] Size of the buffer
//
//Return Values:
//    TRUE: Succeed
//    FALSE: Failed
//    
//Example:
//    MByteToWChar(szW,szA,sizeof(szA)/sizeof(szA[0]));
//---------------------------------------------------------------------------------------
BOOL CUtil::WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize)
{
    DWORD dwMinSize;
    dwMinSize = WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
    if(dwSize < dwMinSize)
    {
        return FALSE;
    }
    WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwSize,NULL,FALSE);
    return TRUE;
}



void CUtil::CreateDirectorySerial(TCHAR *pszPath)
{

    int iBeginCpy = 0;
    int iEndCpy = 0;
    TCHAR szCpy[MAX_PATH] =  {0};
    TCHAR szSource[MAX_PATH] =  {0};

    _tcscpy(szSource,pszPath);

    int iLen = _tcslen(szSource);
    if(szSource[iLen - 1] == '\\')
    {
        szSource[iLen - 1] = ' ';
    }

    while(TRUE)
    {
        iEndCpy = FindString(szSource,TEXT("\\"),iBeginCpy);
            if(iEndCpy == -1)
            {
                break;
            }        

            memset(szCpy,0,sizeof(szCpy));
            _tcsncpy(szCpy, pszPath, iEndCpy + 1);
            CreateDirectory(szCpy,NULL);

            iBeginCpy = iEndCpy + 1;

    }

    if(iEndCpy == -1 && iBeginCpy != 0)
    {
        CreateDirectory(szSource,NULL);
    }
}


//-------------------------------------------------------------------------------------
//Description:
//    Broad the message to the specifies window
//
//Parameters:
//    bctype: [in] Specifies which type of window to receive the message
//    wMsg: [in] Specifies the message to be sent. 
//    wParam: [in] Specifies additional message-specific information. 
//    lParam: [in] Specifies additional message-specific information. 
//---------------------------------------------------------------------------------------
void CUtil::BroadcastMessage(BroadcastType bcType, UINT wMsg, WPARAM wParam, LPARAM lParam)
{
    m_hWndBc = NULL;
    m_wMsgBc = wMsg;
    m_wParamBc = wParam;
    m_lParamBc = lParam;
    m_BcType = bcType;
#ifdef UNDER_CE
    EnumWindows(EnumWindowsProcForBroadcast,NULL);
#endif
}


//--------------------------------------------------------------------------------------
//Description:
//    This function is an application-defined callback function that receives top-level window 
//handles as a result of a call to the EnumWindows function. And the function is only be called
//in the BroadcastMessage() function
//--------------------------------------------------------------------------------------
BOOL CUtil::EnumWindowsProcForBroadcast(HWND hWnd, LPARAM lParam)
{
    if(m_hWndBc == hWnd)
    {
        return FALSE;
    }

    if(m_hWndBc == NULL)
    {
        m_hWndBc = hWnd;
    }

/*
    if(m_BcType == BC_VISIBLE || m_BcType == BC_VISIBLE_NOBASEEXPLORER)
    {
        if(GetWindowLong(hWnd,GWL_STYLE) & WS_VISIBLE)
        {
            if(m_BcType == BC_VISIBLE_NOBASEEXPLORER)
            {
                TCHAR szClsName[MAX_PATH] =  {0};
                GetClassName(hWnd,szClsName,MAX_PATH);
                if(_tcscmp(TEXT("HHTaskBar"),szClsName) == 0 ||
                    _tcscmp(TEXT("DesktopExplorerWindow"),szClsName) == 0 
                    )
                {
                    return TRUE;
                }
            }

            SendMessage(hWnd,m_wMsgBc,m_wParamBc,m_lParamBc);        
        }
    }
    else
*/

	if(m_BcType == BC_ALL)
    {
        PostMessage(hWnd,m_wMsgBc,m_wParamBc,m_lParamBc);
    }

    return TRUE;
}

//-------------------------------------------------------------------------------------
//Description:
//    Delete the no empty directory
//
//Parameters:
//    pszPath: [in] The path of directory
//---------------------------------------------------------------------------------------
void CUtil::DeleteDirectory(const TCHAR *pszPath)
{
    ULONG ulLen = _tcslen(pszPath);
    TCHAR szPathBuf[MAX_PATH] =  {0}; 
    _tcscpy(szPathBuf,pszPath);

    ulLen = _tcslen(szPathBuf);
    if(szPathBuf[ulLen - 1] != '\\')
    {
        szPathBuf[ulLen] = '\\';
        szPathBuf[ulLen + 1] = ' ';
    }
    _tcscat(szPathBuf,TEXT("*.*"));

    WIN32_FIND_DATA fd;
    HANDLE hFind = FindFirstFile(szPathBuf,&fd);
    if(hFind != INVALID_HANDLE_VALUE)
    {
        do {
            TCHAR szNextPath[MAX_PATH] =  {0};
            _tcscpy(szNextPath,pszPath);

            ULONG uLenNext = _tcslen(szNextPath);
            if(szNextPath[uLenNext - 1] != '\\')
            {
                szNextPath[uLenNext] = '\\';
                    szNextPath[uLenNext + 1] = ' ';
            }
            _tcscat(szNextPath,fd.cFileName);

            if(fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
            {        
                //it must be directory                
                DeleteDirectory(szNextPath);
                RemoveDirectory(szNextPath);
            }
            else
            {    
                //it is file 
                DeleteFile(szNextPath);
            }
        }while(FindNextFile(hFind,&fd));
    }

    FindClose(hFind);

    RemoveDirectory(pszPath);
}

BOOL CUtil::InitResXML(CXMLParser &xml, wstring &strFileName,LPCWSTR pStrResType)
{
	BOOL bRet = FALSE;

	TCHAR *pSzText = NULL;

	if(NULL == g_ResDll)
	{
		return FALSE;
	}
	

	if (!strFileName.length())
	{
		return FALSE;
	}

	HRSRC hrSrc = FindResource(g_ResDll, strFileName.c_str(),pStrResType);

	if (hrSrc)
	{
		DWORD dwSize = SizeofResource(g_ResDll, hrSrc)  + 16;
		HGLOBAL hGlob = LoadResource(g_ResDll, hrSrc);

		if (hGlob)
		{
			LPVOID lpLock = LockResource(hGlob);

			if (lpLock)
			{
				pSzText = new TCHAR[dwSize];
				CUtil::MByteToWChar((LPCSTR)lpLock,pSzText,dwSize);
			}
		}
	}

	if(pSzText)
	{
		bRet = xml.SetDoc(wstring(pSzText));
		delete [] pSzText;
		pSzText = NULL;
	}

	if(!bRet)
	{
		//MessageBox(NULL,xml.GetError().c_str(),L"error",MB_OK);
	}

	return bRet;
}

BOOL CUtil::TouchCalibrate()
{
#ifdef UNDER_CE
	typedef BOOL (WINAPI *_TouchCalibrate)();

	HINSTANCE  hinstance = LoadLibrary(_T("coredll.dll")); 
	if  (hinstance == NULL)  
	{  
		return FALSE; 
	}

	_TouchCalibrate TouchCalibrate = NULL; 
	TouchCalibrate = (_TouchCalibrate)GetProcAddress(hinstance , L"TouchCalibrate"); 
	if (TouchCalibrate == NULL)  
	{  
		return FALSE; 
	}

	TouchCalibrate (); 
	FreeLibrary(hinstance );
#else
	MessageBeep(0);
#endif

	return TRUE;
}

int CUtil::GetOPIndexByValue(vector<Option>& ve,DWORD dwValue)
{
	for(int i = 0; i < ve.size(); i++)
	{
		if(dwValue == ve.at(i).dwData)
		{
			return i;
		}
	}
	return 0;
}

int CUtil::GetOPIndexByTxt(vector<Option>& ve,wstring strTxt)
{
	for(int i = 0; i < ve.size(); i++)
	{
		if(strTxt == ve.at(i).strText)
		{
			return i;
		}
	}
	return 0;
}

wstring CUtil::GetResPath()
{
	wstring strTmp;
	strTmp = CUtil::GetCurrentDirectory();
	strTmp += L"\\Config\\";
	strTmp += CConfig::GetInstance()->GetSkin();
	strTmp += L"\\";

	return strTmp;
}

void CUtil::SetResPath( LPCTSTR pStr )
{
	g_strResPath = GetResPath();
}

BOOL CUtil::InitResHandle()
{
#ifdef BITMAP_FROM_FILE
	g_strResPath = GetResPath();
	return TRUE;
#endif

	if(g_ResDll)
	{
		//FreeLibrary(g_ResDll);
		//g_ResDll = NULL;
		return TRUE;
	}

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

	wstring strPath = GetResPath();
	g_strResPath = strPath;

	strPath += L"*.zip";
	hFind = FindFirstFile(strPath.c_str(),&FindFileData);

	if (hFind == INVALID_HANDLE_VALUE) 
	{
		//MessageBox(NULL,L"Can Not Find The Resource File!",L"",MB_OK);
		FindClose(hFind);
		return FALSE;
	} 
	else 
	{
		FindClose(hFind);
	}

	strPath = g_strResPath;
	strPath += L"\\";
	strPath += FindFileData.cFileName;

	g_ResDll = LoadLibraryEx(strPath.c_str(),NULL,LOAD_LIBRARY_AS_DATAFILE);

	return (NULL != g_ResDll);
}

void CUtil::FreeResHandle()
{
	if(g_ResDll)
	{
		FreeLibrary(g_ResDll);
		g_ResDll = NULL;
	}
}

HBITMAP CUtil::LoadBitmapEx(wstring strFileName,BOOL bFromDll)
{

#ifdef BITMAP_FROM_FILE
	bFromDll = FALSE;
#endif

	if(bFromDll)
	{
		//DWORD dwErrorCode =0;
		//HBITMAP hBitmap = NULL;
		//hBitmap = LoadBitmap(m_hResDll,strFileName.c_str());

		/*if(!hBitmap)
		{
		dwErrorCode= GetLastError();
		}*/

		if(!g_ResDll)
		{
			InitResHandle();
		}

		return LoadBitmap(g_ResDll,strFileName.c_str());;
	}
	else
	{
		strFileName = g_strResPath + strFileName;

#ifndef UNDER_CE
		return (HBITMAP)LoadImage(NULL,strFileName.c_str(),IMAGE_BITMAP,0,0,LR_LOADFROMFILE);

#else
		return (HBITMAP)SHLoadDIBitmap(strFileName.c_str());
#endif
	}

	return NULL;
}

BOOL CUtil::EnumDir(list<wstring>& lst,wstring strPath)
{
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

	hFind = FindFirstFile(strPath.c_str(),&FindFileData);

	//hFind = FindFirstFileEx(strPath.c_str(), FindExInfoStandard,&FindFileData, FindExSearchLimitToDirectories,NULL,NULL);

	if(hFind != INVALID_HANDLE_VALUE)
	{
		do{
			if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM || FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
				{
				}
				else
				{
					if(!_tcscmp(FindFileData.cFileName,L"."))
					{

					}
					else if(!_tcscmp(FindFileData.cFileName,L".."))
					{

					}
					else
					{
						lst.push_front(FindFileData.cFileName);
					}
					
				}
			}
		} while (FindNextFile(hFind,&FindFileData)) ;
	}

//#ifndef UNDER_CE
//	if(!PathIsRoot(strPath.c_str()))
//	{
//		lst.push_front(L"..");
//	}
//#endif

	FindClose(hFind);

	return TRUE;
}

BOOL CUtil::FindFile(list<wstring>& lst,wstring strPath,vector<wstring>& veFilter)
{
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

	hFind = FindFirstFile(strPath.c_str(),&FindFileData);

	if(hFind != INVALID_HANDLE_VALUE)
	{
		wstring strExtension;
		int nCount = veFilter.size();
		int i;
		BOOL bFind = FALSE;
		
		do{
			if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM || FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
				{
					
				}
				else
				{
#ifndef UNDER_CE
					if(_tcscmp(FindFileData.cFileName,L".") && _tcscmp(FindFileData.cFileName,L".."))
					{
						lst.push_front(FindFileData.cFileName);
					}
#else
						lst.push_front(FindFileData.cFileName);
#endif
				}
			}
			else
			{
				/*if(FindFileData.dwFileAttributes&FILE_ATTRIBUTE_SYSTEM 
					&& FindFileData.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN)
				{
					continue;
				}*/

				GetFileExtension(FindFileData.cFileName,strExtension);

				if(!strExtension.length())
				{
					continue;
				}

				for(i = 0; i< nCount; i++)
				{
					if(strExtension == veFilter.at(i))
					{
						bFind = TRUE;
						break;
					}
					bFind = FALSE;
				}
				if(bFind)
				{
					lst.push_back(FindFileData.cFileName);
					bFind = FALSE;
				}
			}			
		} while (FindNextFile(hFind,&FindFileData)) ;
	}

//#ifndef UNDER_CE
//	if(!PathIsRoot(strPath.c_str()))
//	{
//		lst.push_front(L"..");
//	}
//#endif

	FindClose(hFind);

	return TRUE;
}

BOOL CUtil::GetFileExtension(wstring strFile,wstring& strExt)
{
	strExt.clear();
	transform(strFile.begin(),strFile.end(),strFile.begin(),tolower);

	int nDotPos = strFile.rfind('.');
	if (nDotPos != wstring::npos)
	{
		strExt = strFile.substr(nDotPos + 1,strFile.length() - nDotPos);
	}
	else
	{
		return FALSE;
	}

	if(!strExt.length())
	{
		return FALSE;
	}

	if(strExt == L".")
	{
		return FALSE;
	}

	return TRUE;
}

void CUtil::TrimFileExtension(wstring& strFile)
{
	int nDotPos = strFile.rfind('.');
	if (nDotPos != wstring::npos)
	{
		strFile = strFile.substr(0,nDotPos);
	}
}

void CUtil::TrimPathRight(wstring& strPath)
{
	int nDotPos = strPath.rfind('\\');
	if (nDotPos != wstring::npos)
	{
		strPath = strPath.substr(0,nDotPos);
	}
}

void CUtil::TrimPathLeft(wstring& strPath)
{
	int nDotPos = strPath.rfind('\\');
	if (nDotPos != wstring::npos)
	{
		strPath = strPath.substr(nDotPos+1,strPath.length());
	}
}

wstring CUtil::GetStorageCardName()
{
	/*CReg reg;

	if(reg.Open(HKEY_LOCAL_MACHINE,L"\\System\\StorageManager\\Profiles\\USBHDProfile"))
	{
		TCHAR szTmp[MAX_PATH];

		if(reg.GetValueSZ(L"Folder",szTmp,MAX_PATH))
		{
			wstring strTmp = szTmp;
			if(strTmp.length())
			{
				return strTmp;
			}
		}
	}*/

	return L"\\Hard Disk";
}

wstring CUtil::GetFlashName()
{
	CReg reg;

	if(reg.Open(HKEY_LOCAL_MACHINE,L"\\System\\StorageManager\\Profiles\\FlashDrv"))
	{
		TCHAR szTmp[MAX_PATH];

		if(reg.GetValueSZ(L"Folder",szTmp,MAX_PATH))
		{
			wstring strTmp = szTmp;
			if(strTmp.length())
			{
				return strTmp;
			}
		}
	}

	return L"ResidentFlash";
}

HBITMAP	CUtil::GetDCBmp(CDC *pDc)
{
	BOOL bRet = FALSE;

	HDC hScrDC = pDc->m_hDC; 

	int nWidth = CUtil::GetScreenWidth();
	int nHeight = CUtil::GetScreenHeight();

	HDC hMemDC = CreateCompatibleDC(hScrDC);
	HBITMAP hBmp  = CreateCompatibleBitmap(hScrDC,nWidth,nHeight);

	if(! hScrDC && hMemDC && hBmp)
	{
		DeleteDC(hScrDC);
		DeleteDC(hMemDC);
		DeleteObject(hBmp);
		return NULL;
	}

	HBITMAP oldBmp = (HBITMAP)SelectObject(hMemDC,hBmp);

	if(BitBlt(hMemDC, 0, 0, nWidth, nHeight,hScrDC, 0, 0, SRCCOPY))
	{
		bRet = TRUE;
	}

	SelectObject(hMemDC,oldBmp);

	//DeleteDC(hScrDC);
	DeleteDC(hMemDC);

	if(bRet)
	{
		return hBmp;
	}

	return  NULL;
}
HBITMAP	CUtil::GetScreenBmp()
{
	BOOL bRet = FALSE;

	HDC hScrDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL); 

	int nWidth = CUtil::GetScreenWidth();
	int nHeight = CUtil::GetScreenHeight();

	HDC hMemDC = CreateCompatibleDC(hScrDC);
	HBITMAP hBmp  = CreateCompatibleBitmap(hScrDC,nWidth,nHeight);

	if(! hScrDC && hMemDC && hBmp)
	{
		DeleteDC(hScrDC);
		DeleteDC(hMemDC);
		DeleteObject(hBmp);
		return NULL;
	}

	HBITMAP oldBmp = (HBITMAP)SelectObject(hMemDC,hBmp);

	if(BitBlt(hMemDC, 0, 0, nWidth, nHeight,hScrDC, 0, 0, SRCCOPY))
	{
		bRet = TRUE;
	}

	SelectObject(hMemDC,oldBmp);

	DeleteDC(hScrDC);
	DeleteDC(hMemDC);

	if(bRet)
	{
		return hBmp;
	}

	return  NULL;
}

BOOL   CUtil::PlayBeepSound(int nSound,int nDuration)
{
	HANDLE hBuzzer;
	hBuzzer = CreateFile(TEXT("BUZ1:"),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
	if ( hBuzzer == INVALID_HANDLE_VALUE)
	{
		return FALSE;
	}
	else
	{
	}

	DWORD freq, dummy;
	freq=nSound;
//	for( freq=100; freq<1100; freq+=100 ) {
		WriteFile( hBuzzer, &freq, sizeof(freq), &dummy, NULL );
		Sleep( nDuration );
	//	printf( "Freq=%d\r\n", freq);
		Sleep( nDuration );
	//};
	CloseHandle( hBuzzer );
	return TRUE;

}
